package com.zjm.find.utils;

import org.springframework.util.ClassUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

public class UploadFile {
    public static Map<String, String> upload(HttpServletRequest request) throws IOException {
        String filePath = "";
        request.setCharacterEncoding("utf-8"); //设置编码
//        String realPath = "c:/images/" + TimeUtils.getNowDatetoString() + "/";
//        String realPath = request.getSession().getServletContext().getRealPath("/upload/");
//        String path = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
        // 项目路径
//        File directory = new File("src/main/resources/static/");
//        String path = directory.getCanonicalPath();
        String path =  System.getProperty("user.dir") + "/src/main/resources/static/img/";
//        System.out.println("存放路径" + path);
        File dir = new File(path);
        //文件目录不存在，就创建一个
        if (!dir.isDirectory()) {
            dir.mkdirs();
        }
        try {
            StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;
            //获取formdata的值
            Iterator<String> iterator = req.getFileNames();
//            String username = request.getParameter("username");
            while (iterator.hasNext()) {
                MultipartFile file = req.getFile(iterator.next());
                String fileName = file.getOriginalFilename();
                //真正写到磁盘上
                String uuid = UUID.randomUUID().toString().replace("-", "");
                String kzm = fileName.substring(fileName.lastIndexOf("."));
                String filename = uuid + kzm;
                File file1 = new File(path + filename);
                OutputStream out = new FileOutputStream(file1);
                out.write(file.getBytes());
                out.close();
                filePath = request.getScheme() + "://" +
                        request.getServerName() + ":"
                        + request.getServerPort()
                        + "/upload/" + filename;
                filePath = "http://localhost:88/" + filename;
                System.out.println("访问图片url:" + filePath);
            }
        } catch (Exception e) {
        }
        Map<String, String> uploadFile = new HashMap<>();
        uploadFile.put("url", filePath);
        return uploadFile;
    }
}
